<template>
	<div class="sc-upload-file">
		<el-upload
			:disabled="disabled"
			:auto-upload="autoUpload"
			:action="action"
			:name="name"
			:data="data"
			:http-request="request"
			v-model:file-list="defaultFileList"
			:show-file-list="showFileList"
			:drag="drag"
			:accept="accept"
			:multiple="multiple"
			:limit="limit"
			:before-upload="before"
			:on-success="success"
			:on-error="error"
			:on-preview="handlePreview"
			:on-exceed="handleExceed"
			:on-remove="removeFile">
			<slot>
				<el-button type="primary" :disabled="disabled" :loading="isLoading">Click to upload</el-button>
			</slot>
			<template #tip>
				<div v-if="tip" class="el-upload__tip">{{tip}}</div>
			</template>
		</el-upload>
		<span style="display:none!important"><el-input v-model="value"></el-input></span>
	</div>
</template>

<script>
	import config from "@/config/upload"

	export default {
		props: {
			isUploadS3: {type: Boolean, default: false},
			isRemoveBlob: { type: Boolean, default: false },
			type: { type: String, default: "" },
			fileType: { type: String, default: "artwork" },
			modelValue: { type: [String, Array], default: "" },
			tip: { type: String, default: "" },
			action: { type: String, default: "" },
			apiObj: { type: Object, default: () => {} },
			name: { type: String, default: config.filename },
			data: { type: Object, default: () => {} },
			accept: { type: String, default: "" },
			maxSize: { type: Number, default: config.maxSizeFile },
			limit: { type: Number, default: 1 },
			autoUpload: { type: Boolean, default: true },
			showFileList: { type: Boolean, default: true },
			drag: { type: Boolean, default: false },
			multiple: { type: Boolean, default: true },
			disabled: { type: Boolean, default: false },
			onSuccess: { type: Function, default: () => { return true } }
		},
		data() {
			return {
				value: "",
				isLoading: false,
				defaultFileList: []
			}
		},
		watch:{
			modelValue(val){
				if(Array.isArray(val)){
					if (JSON.stringify(val) != JSON.stringify(this.formatArr(this.defaultFileList))) {
						this.defaultFileList = val
						this.value = val
					}
				}else{
					if (val != this.toStr(this.defaultFileList)) {
						this.defaultFileList = this.toArr(val)
						this.value = val
					}
				}
			},
			defaultFileList: {
				handler(val){
					if(val&&val[0])this.$emit('getFile',val[0])
					this.$emit('update:modelValue', Array.isArray(this.modelValue) ? this.formatArr(val) : this.toStr(val))
					this.value = this.toStr(val)
				},
				deep: true
			}
		},
		mounted() {
			this.defaultFileList = Array.isArray(this.modelValue) ? this.modelValue : this.toArr(this.modelValue)
			this.value = this.modelValue
		},
		methods: {
			removeFile(){
				this.$emit('removeFile')
			},
			//默认值转换为数组
			toArr(str){
				try{
					var _arr = []
					if(!str)return
					var arr = str.split(",")
					arr.forEach(item => {
						if(item){
							var urlArr = item.split('/');
							var fileName = urlArr[urlArr.length - 1]
							_arr.push({
								name: fileName,
								url: item
							})
						}
					})
					return _arr
				}catch(e){
					console.log(e)
				}
			},
			//数组转换为原始值
			toStr(arr){
				if(!arr)return
				return arr.map(v => v.url).join(",")
			},
			//格式化数组值
			formatArr(arr){
				var _arr = []
				arr.forEach(item => {
					if(item){
						_arr.push({
							name: item.name,
							url: item.url
						})
					}
				})
				return _arr
			},
			before(file){
				this.isLoading = true;
				const maxSize = file.size / 1024 / 1024 < this.maxSize;
				if (!maxSize) {
					this.$message.warning(`${this.$t('components.upload.uploadTips')} ${this.maxSize}MB!`);
					return false;
				}
			},
			success(res, file){
				// if(!this.isRemoveBlob){
					this.isLoading = false;
					this.$emit('onSuccess',res,file,this.defaultFileList)
					// return
				// }
				var os = this.onSuccess(res, file)
				if(os!=undefined && os==false){
					return false
				}
				// var response = config.parseData(res)
				// file.name = response.fileName || res.data.file_id
				// file.url = response.src || res.data.file_id
			},
			error(err){
				this.$notify.error({
					title: this.$t('components.upload.uploadFail'),
					message: err
				})
			},
			beforeRemove(uploadFile){
				return this.$confirm(`${this.$t('components.upload.removeTitle')} ${uploadFile.name} ?`, this.$t('components.upload.title'), {
					type: 'warning',
				}).then(() => {
					return true
				}).catch(() => {
					return false
				})
			},
			handleExceed(){
				this.$message.warning(this.$t('components.upload.maxError'))
			},
			handlePreview(uploadFile){
				window.open(uploadFile.url)
			},
			async request(param){
				console.log('file type',param)
				/**type
				 * 1:画像,
				 * 2:映像,
				 * 3:音声,
				 * 4:電子書籍,
				 * 9:その他,
				 */
				/**category
					作品：1、
					附件：5、
					头像: 3,
					背景图像：4，
					证书：6张，
					证书缩略图：7，
					缩略图：2
				 */
				 const fileType = {
					image: 1,
					audio: 3,
					eBook: 4,
					other: 9,
					video: 2,
					pvideo: 8
				}
				const fileCategory = {
					artwork: 1,
					attachment: 5,
					avatar: 3,
					bgImage: 4,
					certificate: 6,
					certificateThumbnail: 7,
					thumbnail: 2,
					previewVideo: 11
				}
				var apiObj = config.apiObj;
				if(this.apiObj){
					apiObj = this.apiObj;
				}
				const data = {};
				// const data = new FormData();
				// data.append(param.filename, param.file,param.file.type);
				for(let i=0;i<param.file.type.split('/').length;i++){
					if(['pdf','txt','xlsx'].includes(param.file.type.split('/')[i])){
						data.type = 4
					}else if(['jpg','jpeg','png','gif','webp','tiff','bmp','svg'].includes(param.file.type.split('/')[i])){
						data.type = 1
					}else {
						data.type = this.type? this.type : fileType[(param.file.type.split('/')[0])]?fileType[(param.file.type.split('/')[0])]:9;
					}
				}
				data.file = param.file;
        data.category = fileCategory[this.fileType];

				// var apiObj = config.apiObjFile;
				// if(this.apiObj){
				// 	apiObj = this.apiObj;
				// }
				// const data = new FormData();
				// data.append(param.filename, param.file);
				// for (const key in param.data) {
				// 	data.append(key, param.data[key]);
				// }
				if(this.action&&this.action!='#')apiObj=this.action;
				// 开启注释 旧版
				if(this.action == 'fileType'){
					// let params = `?filename=${data.file.name}&category=${data.category}&type=${data.type}`;
					// const res = await this.$API.upload.setFile.get(params);
					// if(res.path){
						
						param.onSuccess('OK',data)
					// }
				} else {
					if(this.type) {
						let params = `?filename=${data.file.name}&category=${data.category}&type=${data.type}`;
						const res = await this.$API.common.setFile.get(params);
						if(res.path){
							if(this.isUploadS3){
								this.uploadS3(param.file, res)
							}else{
								param.onSuccess(res)
							}
						}
					} else {
						apiObj.post(data, {
							onUploadProgress: e => {
								const complete = parseInt(((e.loaded / e.total) * 100) | 0, 10)
								param.onProgress({percent: complete})
							}
						}).then(res => {
							var response = config.parseData(res);
							if(response.code == config.successCode){
								param.onSuccess(res)
							}else{
								param.onError(response.msg || this.$t('components.upload.error'))
							}
						}).catch(err => {
							param.onError(err)
						})
					}
				}
				console.log(apiObj)
			},
			// 直传到s3
			async uploadS3(param,res){
				console.log('开始上传...',param)
				const fileType = {
					image: 1,
					audio: 3,
					eBook: 4,
					other: 9,
					video: 2,
					pvideo: 8
				}
				const fileCategory = {
					artwork: 1,
					attachment: 5,
					avatar: 3,
					bgImage: 4,
					certificate: 6,
					certificateThumbnail: 7,
					thumbnail: 2,
					previewVideo: 11
				}
				let data = {};
				for(let i=0;i<param.type.split('/').length;i++){
					if(['pdf','txt','xlsx'].includes(param.type.split('/')[i])){
						data.type = 4
					}else if(['jpg','jpeg','png','gif','webp','tiff','bmp','svg'].includes(param.type.split('/')[i])){
						data.type = 1
					}else {
						data.type = this.type? this.type : fileType[(param.type.split('/')[0])]?fileType[(param.type.split('/')[0])]:9;
					}
				}
				data.file = param;
				data.category = fileCategory[this.fileType];
			
				let fileData = new FormData();
				fileData.file = param;
				for (const key in param) {
					fileData.append(key, param[key]);
				}
				this.$API.upload.awsUploadFile.put(res.path,fileData.file,{'Content-Type': fileData.file.type}).then(response => {
					console.log(response)
					this.$emit('onSuccess',res.fileId)
				}).catch(err => {
					console.log('上传aws异常',err)
				})
			},

		}
	}
</script>

<style scoped>
	.el-form-item.is-error .sc-upload-file:deep(.el-upload-dragger) {border-color: var(--el-color-danger);}
	.sc-upload-file {width: 100%;}
	.sc-upload-file:deep(.el-upload-list__item) {transition: none !important;}
</style>
